# !/usr/bin/env python
# coding:utf-8
"""
    Author = 上善若水(QQ:564667570)
    Affiliation = Institute of Subtropical Agriculture, Chinese Academy of Sciences
    Time = '2018-3-26, 23:14'
"""

# 1. PKCS#5(选择一种hash算法)加密算法加密你的中文名字,写出代码
# method one
import binascii, hashlib

def question_01(name):
    if isinstance(name, (str, bytes)):
        pk = hashlib.pbkdf2_hmac('sha512', b'yong', name, iterations=100, dklen=32)
        print(type(pk))
        print(binascii.hexlify(pk))

if __name__=='__main__':
    question_01(b'hello world')

# method two
from pbkdf2 import crypt
print(crypt("上善若水", "XXXXXXXX", iterations=100))

# 2. 创建文件test.py,写入一些数据,并计算该文件的md5值

import hashlib
with open('test.py', 'w') as myfile:   # 把文件名称更新到MD5
    myfile.write('this is my favorite site')

with open('test.py', 'rb') as file:   #
    test_content = hashlib.md5(file.read())   # 读取所有的数据 ---> 更新到md5对象
    print(test_content.hexdigest())

# 3. 遵循上下文管理协议,自己编写一个类,去创建一个上下文管理器,然后自己使用看看
#    方式1:普通方式
#    方式2:使用contextmanager

# Method_01. normal method
class MyClass(object):
    def __init__(self, a_list):
        print("First. to set the parameters")
        self.a_list = a_list

    def __enter__(self):
        print('Second. to execute the code')
        self.a_list.append('next')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('to exit the code')
        self.a_list = None
        if exc_type:
            print(exc_type, exc_val, exc_tb)
        else:
            print('execution code is done')

    def work_function(self):    # the function
        for item in self.a_list:
            print(item)

with MyClass([1, 2, 4, 'a', 9]) as myfile:
    myfile.work_function()

# Method02: Using contextmanager
from contextlib import contextmanager

class MySecondClass(object):
    def __init__(self, b_list):
        print('to initiate the code')
        self.b_list = b_list

    def workFunction(self):
        print('===========dealing with the parameters=================')
        for item02 in self.b_list:
            print(item02)

@contextmanager
def make_context(list):
    print('start the execution code')
    myclass = MySecondClass(list)
    yield myclass
    print('the execution code is finished')

with make_context([2, 34, 521, 'aew', 2]) as MyFile:
    MyFile.workFunction()


# 4. 使用colorama模块使用多颜色输出
from colorama import Fore, Back, Style

print(Fore.BLUE + 'Hola, Soy Yong, como estas?')
print(Fore.RED + 'Hola, Soy Yong, como estas?')
print(Fore.LIGHTBLACK_EX + 'Hola, Soy Yong, como estas?')
print(Fore.YELLOW + 'Hola, Soy Yong, como estas?')

print(Back.YELLOW + "No te conozco!")
print(Back.BLACK + "No te conozco!")
print(Back.MAGENTA + "No te conozco!")
print(Back.GREEN + "No te conozco!")

print(Style.RESET_ALL)
print('Normal color')